package cn.haoma.base.utils;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * Created by ilioili on 2015/6/30.
 */
public class ObjUtil {
    public static boolean delete(String key) {
        try {
            File dir = Environment.getExternalStorageDirectory();
            dir.mkdirs();
            File file = new File(dir, Integer.toOctalString(key.hashCode()));
            if (file.exists()) file.delete();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Serializable get(String key) {
        try {
            File dir = Environment.getExternalStorageDirectory();
            dir.mkdirs();
            File file = new File(dir, Integer.toOctalString(key.hashCode()));
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream oos = new ObjectInputStream(fis);
            Serializable serializable = (Serializable) oos.readObject();
            fis.close();
            return serializable;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean save(String key, Serializable data) {
        try {
            File dir = Environment.getExternalStorageDirectory();
            dir.mkdirs();
            File file = new File(dir, Integer.toOctalString(key.hashCode()));
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(data);
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
